﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace DatabaseBackup.Library
{
    public class TransactionLogBackup
    {
        public static void PerformTransactionLogBackup()
        {
            try
            {
                using (SqlConnection con = new SqlConnection(Helpers.ConnectionString))
                {
                    string[] databases = Helpers.Databases;

                    for (int i = 0; i < databases.Count(); i++)
                    {
                        string fileName = string.Format("T-{0}{1:yyyyMMddHHmm}", databases[i], DateTime.UtcNow);

                        StringBuilder query = new StringBuilder();

                        query.Append("BACKUP LOG " + databases[i]);
                        query.Append(string.Format(@" TO DISK = '{0}{1}'", Helpers.BackupFolder, fileName + ".bak"));

                        SqlCommand cmd = new SqlCommand(query.ToString(), con);

                        con.Open();
                        cmd.ExecuteNonQuery();
                    }
                }

                FileHistoryCleanup.CleanOldFiles(FileType.TransactionLogBackup);
            }

            catch (Exception ex)
            {
                ErrorHandler.AddToErrorLog(ex, BackupType.TransactionLog);
            }
        }
    }
}
